package com.lagou.edu.mvcFramework.pojo;

import com.lagou.edu.mvcFramework.exception.PermissionException;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author stevejson
 *
 * 参数handler方法相关的信息
 */
public class Handler {
    /**
     * controller 标记的类的对象
     */
    private Object controller;
    /**
     * MyRequestMapping  标记的method
     */
    private Method method;
    /**
     * url
     */
    private Pattern pattern;
    /**
     * 参数顺序
     */
    private Map<String, Integer> paramIndexMapping;

    private Set<String> permissionUsers;

    public Handler(Object controller, Method method, Pattern pattern, Set<String> permissionUsers) {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        this.paramIndexMapping = new HashMap<>();
        this.permissionUsers = permissionUsers;
    }

    public Object invoke(String userName, Object... args) throws Exception{
        if(!permissionUsers.isEmpty() && StringUtils.isBlank(userName)){
            throw new PermissionException("权限校验，用户名不能为空");
        }
        if (!permissionUsers.isEmpty() && !permissionUsers.contains(userName)) {
            throw new PermissionException(userName + " 未授权登录");
        }
        return this.method.invoke(this.controller, args);
    }

    public Set<String> getPermissionUsers() {
        return permissionUsers;
    }

    public void setPermissionUsers(Set<String> permissionUsers) {
        this.permissionUsers = permissionUsers;
    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        this.controller = controller;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map<String, Integer> paramIndexMapping) {
        this.paramIndexMapping = paramIndexMapping;
    }
}
